package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import com.sky.utils.UploadToLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 冰白寒祭
 * @date 2023-08-31 18:58:47
 * @description 通用接口
 */

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Value("${server.port}")
    private String serverPort;
    @Value("${spring.web.resources.static-locations}")
    private String savePathArr;
    @Value("${remoteStorage.on-off}")
    private boolean remoteStorage;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传{}", file);
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取文件后缀
        assert originalFilename != null;
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构建新文件名称
        String objectName = UUID.randomUUID() + extension;
        String filePath;

        // 判断仓库地址
        if (remoteStorage) {
            try {
                log.info("文件上传到远程仓库");
                filePath = aliOssUtil.upload(file.getBytes(), objectName);
                return Result.success(filePath);
            } catch (IOException e) {
                log.error("文件上传失败,{}","堆栈信息:",e);
            }
        } else {
            // 本地仓库
            log.info("文件上传到本地仓库");
            // 文件请求路径
            UploadToLocal uploadToLocal = new UploadToLocal();
            String savePath = savePathArr.substring(savePathArr.indexOf(":") + 1);
            uploadToLocal.setSavePath(savePath);
            uploadToLocal.setServerPort(serverPort);
            try {
                filePath = uploadToLocal.uploadLocal(file, objectName);
                return Result.success(filePath);
            } catch (IOException e) {
                log.error("文件上传失败,{}","堆栈信息:",e);
            }
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
